﻿// =====================================================================
// <copyright file="JsonHelper.cs" author="David R. Guindo">
// 	Copyright (C) 2013. All rights reserved.
// </copyright>
// =====================================================================
// This code is released under the terms of the Apache 2.0 license, 
// http://apache.org/licenses/LICENSE-2.0.html
// =====================================================================

namespace AppBlock.Core
{
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using Newtonsoft.Json;

    /// <summary>
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        ///     Gets the properties json.
        /// </summary>
        /// <param name="json"> The json. </param>
        /// <returns> </returns>
        public static IDictionary<string, T> GetProperties<T>(string json)
        {
            IDictionary<string, T> values = JsonConvert.DeserializeObject<IDictionary<string, T>>(json);
            return values;
        }

        /// <summary>
        ///     JSON Deserialization
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            var ser = new DataContractJsonSerializer(typeof (T));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var obj = (T) ser.ReadObject(ms);
            return obj;
        }

        /// <summary>
        ///     Jsons the serializer.
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="t"> The t. </param>
        /// <returns> </returns>
        public static string JsonSerializer<T>(T t)
        {
            var ser = new DataContractJsonSerializer(typeof (T));
            var ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        ///     Serializes the properties json.
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="values"> The values. </param>
        /// <returns> </returns>
        public static string SerializeProperties<T>(IDictionary<string, T> values)
        {
            string json = JsonConvert.SerializeObject(values, Formatting.Indented);
            return json;
        }
    }
}